<?php
namespace common\models;

use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
use yii\base\InvalidArgumentException;
use yii\filters\auth\HttpHeaderAuth;

/**
 * User model
 *
 * @property integer $id
 * @property string $username
 * @property string $password_hash
 * @property string $password_reset_token
 * @property string $verification_token
 * @property string $email
 * @property string $auth_key
 * @property integer $status
 * @property integer $created_at
 * @property integer $updated_at
 * @property string $password write-only password
 */
class User extends ActiveRecord implements IdentityInterface
{
    const STATUS_INACTIVE=0;
    const STATUS_ACTIVE=1;
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%user}}';
    }

    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            ['status', 'default', 'value' => self::STATUS_INACTIVE],
            ['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_INACTIVE]],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE, 'deleted_at' => 0]);
    }

    /**
     * {@inheritdoc}
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }

    /**
     * {@inheritdoc}
     */
    public function getId()
    {
        return $this->getPrimaryKey();
    }

    /**
     * {@inheritdoc}
     */
    public function getAuthKey()
    {
        return $this->hasAttribute('auth_key') ? $this->auth_key : null;
    }

    /**
     * {@inheritdoc}
     */
    public function validateAuthKey($authKey)
    {
        return $authKey && $this->getAuthKey() === $authKey;
    }

    /**
     * 生成记住密码的验证key
     */
    public function generateAuthKey()
    {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }

    /**
     * 生成登录密码
     */
    public function generatePasswordHash($password, $salt = null)
    {
        $security = Yii::$app->security;
        $cost = 16;
        if(!$salt){
            $salt = $security->generateRandomKey($cost / 2);
        }
        else{
            $cost = strlen($salt);
        }
        if($cost > 16 || $cost < 4){
            throw new InvalidArgumentException('salt长度必须在4和16之间！');
        }
        $passwordHash = bin2hex($security->pbkdf2('sha256', $password, $salt, 1000 , 34 - intval($cost / 2)));
        $prefix = sprintf('$%02d$', $cost);
        return $prefix . $salt . $passwordHash;
    }


    /**
     * 验证密码
     *
     * @param string $password password to validate
     * @return bool if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        $cost = intval(substr($this->password, 1, 2));
        $salt = substr($this->password, 4, $cost);
        $passwordHash = $this->generatePasswordHash($password, $salt);
        return $passwordHash == $this->password;
    }

}
